<template>
    <MyDialog ref="myDialog" title="分配角色" width="480px" :on-confirm="confirm" :on-cancel="clearData">
        <MyForm ref="myForm" labelWidth="0px" :form-data="formData" :form-item-list="formItemList"></MyForm>
    </MyDialog>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
interface FormData {
    id: string;
    roleIdList: string[];
}

const emit = defineEmits<{
    (event: 'complete', value: boolean): void;
}>();

const formData: FormData = {
    id: '',
    roleIdList: [],
};

const formItemList = ref<MyComment.FormItemProps<FormData>[]>([
    {
        prop: 'roleIdList',
        label: '',
        type: 'checkbox',
        data: [],
        contentExtends: { width: '112px' } as MyComment.FormItemContentExtends['checkbox'],
    },
]);

const myDialog = ref<MyComment.DialogInstance>();
const myForm = ref<MyComment.FormInstance<FormData>>();

const getRoleList = async () => {
    const res = await MyService.account.getRoleList({ searchKey: '', current: 1, size: 10 });
    if (res.code === 200 && Array.isArray(res.data.records)) {
        formItemList.value[0].data = res.data.records.map((item) => ({ label: item.name || '', value: item.id || '' }));
    } else {
        formItemList.value[0].data = [];
    }
};

const confirm = async (): Promise<boolean> => {
    let result = (await myForm.value?.validate()) || false;
    if (result) {
        const data = myForm.value?.getData();
        if (data) {
            const submitData = {
                id: data.id,
                roleIdList: data.roleIdList,
            };
            const res = await MyService.account.assignRoles(submitData);
            if (res.code === 200) {
                emit('complete', true);
                return true;
            } else {
                ElMessage.error({
                    message: res.msg || '分配角色失败',
                });
                emit('complete', false);
                return false;
            }
        } else {
            emit('complete', false);
            return false;
        }
    }
    return result;
};

const open = (userId: string, roleIdList: string[]) => {
    formData.id = userId;
    formData.roleIdList = roleIdList;
    myDialog.value?.open();
};

const clearData = () => {};

defineExpose({
    open,
});
onBeforeMount(() => {
    getRoleList();
});
</script>

<style scoped></style>
